<template>
  <div class="app_main">
    <div class="searchForm_box">
      <el-form ref="searchForm" :inline="true" size="mini" :model="listParams">
        <el-form-item label="行业：" prop="industry_id">
          <el-select v-model="listParams.industry_id" placeholder="请选择客户行业">
            <el-option
              v-for="item in industry_dict"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetForm('searchForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin: 10px auto">
      <!--      <el-button type="primary" size="mini" @click.native="showDialog">添加折扣</el-button>-->
      <!--      <el-badge :value="count" class="item" v-if="count != 0">-->
      <!--        <el-button type="primary" size="small" @click.native="showFlowDialog">申请列表</el-button>-->
      <!--      </el-badge>-->
      <!--      <el-button v-else type="primary" size="small" @click.native="showFlowDialog">申请列表</el-button>-->
    </div>
    <div class="data_box">
      <el-table ref="table" size="mini" v-loading="tableLoading" border :data="tableData" :max-height="height">
        <el-table-column label="行业" align="center" prop="industry_name" fixed="left" width="150"></el-table-column>
        <el-table-column v-for="item in mediaTypeSpecArr" :key="item.id" :label="item.media_type_spec_name"
                         align="center" min-width="250"
        >
          <template slot-scope="scope">
            <div v-if="scope.$index===0" class="align-start">
              <el-tag v-if="scope.row[item.id]!==undefined && scope.row[item.id].price_day !== null"
                      size="mini" :type="scope.row[item.id].price_day?'':'info'"
              >
                刊例价：{{
                  scope.row[item.id].price_day ? scope.row[item.id].price_day + '/元/天' : '暂未填写/元/天'
                }}
              </el-tag>
              <el-tag v-if="scope.row[item.id]!==undefined && scope.row[item.id].price_week !== null"
                      size="mini" :type="scope.row[item.id].price_week?'':'info'"
              >
                刊例价：{{
                  scope.row[item.id].price_week ? scope.row[item.id].price_week + '/元/周' : '暂未填写/元/周'
                }}
              </el-tag>
              <el-tag v-if="scope.row[item.id]!==undefined && scope.row[item.id].price_month !== null"
                      size="mini" :type="scope.row[item.id].price_month?'':'info'"
              >
                刊例价：{{
                  scope.row[item.id].price_month ? scope.row[item.id].price_month + '/元/月' : '暂未填写/元/月'
                }}
              </el-tag>
            </div>
            <div v-if="scope.$index!==0" class="align-start">
              <el-tag
                size="mini"
                :type="scope.row[item.id] && scope.row[item.id].discount?'warning':'info'"
              >折扣：{{ scope.row[item.id] && scope.row[item.id].discount ? scope.row[item.id].discount + '%' : '暂未填写' }}
              </el-tag>
            </div>
            <div v-if="scope.$index!==0" class="align-start">
              <div>
                <el-tag
                  v-if="scope.row[item.id]!==undefined && scope.row[item.id].discount&& scope.row[item.id].price_day !== null"
                  size="mini" :type="scope.row[item.id].price_day?'success':'info'"
                >
                  折扣价：{{
                    scope.row[item.id].price_day ? getPriceAfterDiscount(scope.row[item.id].discount, scope.row[item.id].price_day) + '元/天' : '暂未填写/元/天'
                  }}
                </el-tag>
              </div>
              <div>
                <el-tag
                  v-if="scope.row[item.id]!==undefined && scope.row[item.id].discount && scope.row[item.id].price_week !== null"
                  size="mini" :type="scope.row[item.id].price_week?'success':'info'"
                >
                  折扣价：{{
                    scope.row[item.id].price_week ? getPriceAfterDiscount(scope.row[item.id].discount, scope.row[item.id].price_week) + '元/周' : '暂未填写/元/周'
                  }}
                </el-tag>
              </div>
              <div>
                <el-tag
                  v-if="scope.row[item.id]!==undefined && scope.row[item.id].discount && scope.row[item.id].price_month !== null"
                  size="mini" :type="scope.row[item.id].price_month?'success':'info'"
                >
                  折扣价：{{
                    scope.row[item.id].price_month ? getPriceAfterDiscount(scope.row[item.id].discount, scope.row[item.id].price_month) + '元/月' : '暂未填写/元/月'
                  }}
                </el-tag>
              </div>
              <div v-if="!scope.row[item.id].can_edit">
                <el-tag :type="scope.row[item.id].red_line_price?'danger':'info'" size="mini">
                  红线价：{{ scope.row[item.id].red_line_price ? scope.row[item.id].red_line_price + '元/月' : '暂未填写' }}
                </el-tag>
                <el-button v-permission="'offer_add_and_edit'" v-show="scope.row[item.id].red_line_price === null" type="text"
                           @click="showInput(scope.row[item.id])" size="mini" style="margin-left: 10px"
                >填写
                </el-button>
                <el-button v-permission="'offer_add_and_edit'" v-show="scope.row[item.id].red_line_price !== null" type="text" style="margin-left: 10px"
                           @click="showInput(scope.row[item.id])" size="mini"
                >修改
                </el-button>
              </div>
              <div v-else>
                <el-input v-model="scope.row[item.id].fill_text" size="mini">
                  <template slot="append">元/月</template>
                  <template slot="prepend">红线价</template>
                </el-input>
                <el-button-group>
                  <el-button style="margin-left: 10px"
                             @click="saveRedLinePrice(scope.row[item.id].fill_text,scope.row.industry_id,item.id,scope.row[item.id])"
                             type="text"
                             size="mini"
                  >保存
                  </el-button>
                  <el-button
                    @click="scope.row[item.id].can_edit = false;scope.row[item.id].fill_text = scope.row[item.id].red_line_price"
                    type="text" size="mini" style="margin-left: 10px"
                  >取消
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="100">
          <template slot-scope="scpoe">
            <el-button v-permission="'offer_add_and_edit'" v-if="scpoe.$index!==0" type="primary" size="mini" class="el-icon-edit" @click="edit(scpoe.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="报价详情" :visible.sync="centerDialogVisible" width="70%" center top="100px" @close="closeDialog">
      <div style="height: 600px;overflow-y: auto">
        <el-form ref="offerForm" :model="offer" :inline="true" :disabled="offerDisabled" :rules="rules">
          <div style="width: 300px;margin: 0px auto">
            <el-form-item label="行业类型" prop="industry_id">
              <el-select v-model="offer.industry_id" placeholder="请选择行业类型" :disabled="is_edit">
                <el-option v-for="item in industry_dict" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <el-form :model="tmp" ref="tmpForm">
          <table class="mailTable">
            <tr class="firstTr">
              <td class="column firstTd">
                <div>价格配置名称</div>
              </td>
              <td class="column">
                <div>折扣</div>
              </td>
              <td class="column">
                <div>天/价格</div>
              </td>
              <td class="column">
                <div>周/价格</div>
              </td>
              <td class="column">
                <div>月价格</div>
              </td>
              <td class="column">
                <div>红线价</div>
              </td>
            </tr>
            <tr v-for="(item,index) in tmp.offerArr">
              <td class="column firstTd">
                <div>
                  {{ item.media_type_spec_name }}
                </div>
              </td>
              <td class="column">
                <div>
                  <el-form-item :prop="'offerArr.' + index + '.discount'"
                                :rules="{required: true, message: '折扣不能为空', trigger: 'blur'}"
                  >
                    <el-input v-model="tmp.offerArr[index].discount" placeholder="请输入折扣" style="width: 180px"
                              size="small"
                              step="0.01" type="number"
                    >
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </div>
              </td>
              <td class="column">
                <el-tag v-show="!item.price_day" size="mini">此类型无此价格</el-tag>
                <el-tag v-show="item.price_day" size="mini">刊例价{{ item.price_day }}/元/天</el-tag>
                <el-tag v-show="item.price_day && (item.discount === null || item.discount ==='')" type="warning"
                        size="mini"
                >请先填写折扣
                </el-tag>
                <el-tag v-show="item.price_day && item.discount !== null && item.discount !==''" type="success"
                        size="mini"
                >
                  折扣后价格{{ getPriceAfterDiscount(item.discount, item.price_day) }}/元/天
                </el-tag>
              </td>
              <td class="column">
                <el-tag v-show="!item.price_week" size="mini">此类型无此价格</el-tag>
                <el-tag v-show="item.price_week" size="mini">刊例价{{ item.price_week }}/元/周</el-tag>
                <el-tag v-show="item.price_week && (item.discount === null || item.discount ==='')" type="warning"
                        size="mini"
                >请先填写折扣
                </el-tag>
                <el-tag v-show="item.price_week && item.discount !== null && item.discount !==''" type="success"
                        size="mini"
                >
                  折扣后价格{{ getPriceAfterDiscount(item.discount, item.price_week) }}/元/周
                </el-tag>
              </td>
              <td class="column">
                <el-tag v-show="!item.price_month" size="mini">此类型无此价格</el-tag>
                <el-tag v-show="item.price_month" size="mini">刊例价{{ item.price_month }}/元/月</el-tag>
                <el-tag v-show="item.price_month && (item.discount === null || item.discount ==='')" type="warning"
                        size="mini"
                >请先填写折扣
                </el-tag>
                <el-tag v-show="item.price_month && item.discount !== null && item.discount !==''" type="success"
                        size="mini"
                >
                  折扣后价格{{ getPriceAfterDiscount(item.discount, item.price_month) }}/元/月
                </el-tag>
              </td>
              <td class="column">
                <el-tag :type="item.red_line_price?'danger':'info'" size="mini">
                  红线价：{{ item.red_line_price ? item.red_line_price + '元/月' : '暂未填写' }}
                </el-tag>
              </td>
            </tr>
          </table>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button v-if="!offerDisabled" type="primary" @click="submit">保存到草稿箱</el-button>
        <el-button v-if="!offerDisabled" type="primary" @click="saveAndStartFlow">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { page as List, settingsRedLinePrice } from '@/api/offer/offer'
import { list_all3rd_bycode } from '@/api/business/setting/dict'
import { cloneDeep } from 'lodash'
import { save, saveTmp } from '@/api/offer/offerFlow'
import { multiply } from '@/utils/amount'
import { all } from '@/api/system/media_type_spec_price'

export default {
  name: 'IndexVue',
  data() {
    return {
      listParams: {
        industry_id: null
      },
      flowListParams: {
        page: 1,
        page_size: 10,
        is_check_page: false
      },
      // 行业字典
      industry_dict: [],
      // 媒体类型字典
      media_dict: [],
      tableData: [],
      centerDialogVisible: false,
      offer: {
        industry_id: null,
        offerTmps: [],
        created: 1
      },
      offerArr: [],
      tmp: {
        offerArr: []
      },
      flowTableData: [],
      tableLoading: false,
      flowDialogVisible: false,
      total: null,
      flowTableLoading: false,
      offerDisabled: false,
      rules: {
        industry_id: [
          { required: true, message: '请选择行业', trigger: 'change' }
        ]
      },
      is_edit: false,
      count: 0,
      companyMap: new Map([
        ['1-1', ''],
        ['2-1', '幅/'],
        ['3-1', '幅/'],
        ['7-1', ''],
        ['8-1', '幅/'],
        ['9-1', '幅/'],
        ['10-1', '幅/'],
        ['11-1', ''],
        ['12-1', '幅/'],
        ['13-1', '幅/'],
        ['1-0', '组/'],
        ['2-0', '组/'],
        ['3-0', '组/']
      ]),
      mediaTypeSpecArr: [],
      height: 100
    }
  },
  created() {
    this.initIndustryDict()
    this.getList()
    this.getMediaTypeSpecArr()
    this.height = window.innerHeight - 170
  },
  methods: {
    getList() {
      this.tableLoading = true
      this.tableData = []
      List(this.listParams).then(
        res => {
          this.tableData.push(Object.assign({}, res.data[0]))
          this.tableData[0].industry_name = '刊例总价'
          this.tableData = this.tableData.concat(res.data)
          this.tableData.forEach(item => {
            for (let itemKey in item) {
              if (!isNaN(itemKey)) {
                this.$set(item[itemKey], 'fill_text', item[itemKey].red_line_price)
                this.$set(item[itemKey], 'can_edit', false)
              }
            }
          })
          console.log(this.tableData)
          this.$nextTick(() => {
            this.$refs.table.doLayout() // 解决表格错位
            this.tableLoading = false
          })
        }
      ).catch(() => {
        this.tableLoading = false
      })
    },
    closeDialog() {
      this.offerDisabled = false
      this.offer.industry_id = null
      this.offer.offerTmps = []
      this.offer.created = 1
      this.is_edit = false
    },
    edit(row) {
      this.offer.industry_id = row.industry_id
      this.centerDialogVisible = true
      this.offer.created = 0
      this.tmp.offerArr = []
      this.is_edit = true
      for (let i = 0; i < this.mediaTypeSpecArr.length; i++) {
        const tmp = row[this.mediaTypeSpecArr[i].id]
        if (tmp !== undefined) {
          this.tmp.offerArr.push({
            media_type_spec_name: this.mediaTypeSpecArr[i].media_type_spec_name,
            media_type_spec_price_id: this.mediaTypeSpecArr[i].id,
            price_day: tmp.price_day,
            price_week: tmp.price_week,
            price_month: tmp.price_month,
            discount: tmp.discount,
            red_line_price: tmp.red_line_price
          })
        } else {
          this.tmp.offerArr.push({
            media_type_spec_name: this.mediaTypeSpecArr[i].media_type_spec_name,
            media_type_spec_price_id: this.mediaTypeSpecArr[i].id,
            price_day: this.mediaTypeSpecArr[i].price_day,
            price_week: this.mediaTypeSpecArr[i].price_week,
            price_month: this.mediaTypeSpecArr[i].price_month,
            discount: null,
            red_line_price: null
          })
        }
      }
      this.$nextTick(() => {
        this.$refs['offerForm'].clearValidate()
        this.$refs['tmpForm'].clearValidate()
      })
    },
    handleSizeChange(val) {
      this.flowListParams.page_size = val
      this.getFlowList()
    },
    handleCurrentChange(val) {
      this.flowListParams.page = val
      this.getFlowList()
    },
    showDialog() {
      this.centerDialogVisible = true
      this.tmp.offerArr = cloneDeep(this.offerArr)
      this.$nextTick(() => {
        this.$refs['offerForm'].clearValidate()
        this.$refs['tmpForm'].clearValidate()
      })
    },
    showFlowDialog() {
      this.getFlowList()
      this.flowDialogVisible = true
    },
    search() {
      this.getList()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.getList()
    },
    // 初始化行业字典
    initIndustryDict() {
      list_all3rd_bycode({ code: 'khxg-hy' }).then(
        res => {
          this.industry_dict = res.data.map(item => (
            {
              id: item.id,
              name: item.name
            }
          ))
        }
      )
    },
    submit() {
      this.$refs.offerForm.validate((valid) => {
        if (valid) {
          this.$refs.tmpForm.validate(flag => {
            if (flag) {
              this.$confirm('确定保存到草稿箱?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                const loading = this.$loading({
                  lock: true,
                  text: '提交中',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)'
                })
                for (let i = 0; i < this.tmp.offerArr.length; i++) {
                  this.tmp.offerArr[i].industry_id = this.offer.industry_id
                }
                this.offer.offerTmps = cloneDeep(this.tmp.offerArr)
                save(this.offer).then(
                  res => {
                    if (res.data) {
                      // this.initNoRead()
                      this.$message({
                        message: '操作成功',
                        type: 'success'
                      })
                    } else {
                      this.$message.error('操作失败')
                    }
                    this.centerDialogVisible = false
                    loading.close()
                  }
                ).catch(() => {
                  loading.close()
                  this.$message.error('操作失败')
                })
              }).catch(() => {
              })
            }
          })
        }
      })
    },
    saveAndStartFlow() {
      this.$refs.offerForm.validate((valid) => {
        if (valid) {
          this.$refs.tmpForm.validate(flag => {
            if (flag) {
              this.$confirm('确定提交?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                const loading = this.$loading({
                  lock: true,
                  text: '提交中',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)'
                })
                for (let i = 0; i < this.tmp.offerArr.length; i++) {
                  this.tmp.offerArr[i].industry_id = this.offer.industry_id
                }
                this.offer.offerTmps = cloneDeep(this.tmp.offerArr)
                saveTmp(this.offer).then(
                  res => {
                    if (res.data) {
                      this.$message({
                        message: '操作成功',
                        type: 'success'
                      })
                    } else {
                      this.$message.error('操作失败')
                    }
                    this.centerDialogVisible = false
                    loading.close()
                  }
                ).catch(() => {
                  loading.close()
                  this.$message.error('操作失败')
                })
              }).catch(() => {
              })
            }
          })
        }
      })
    },
    /**
     * 获取折扣后价格
     */
    getPriceAfterDiscount(discount, price) {
      if (discount == null || discount == '' || price == null || price == '') {
        return ''
      }
      let s = '0.' + discount
      return multiply(s, price)
    },
    getMediaTypeSpecArr() {
      all().then(res => {
        this.mediaTypeSpecArr = res.data
        this.offerArr = res.data.map(item => {
          return Object.assign({ media_type_spec_price_id: item.id, discount: null }, item)
        })
      })
    },
    saveRedLinePrice(fill_text, industry_id, media_type_spec_price_id, obj) {
      this.$confirm('确定保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '提交中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        settingsRedLinePrice({
          industry_id: industry_id,
          media_type_spec_id: media_type_spec_price_id,
          red_line_price: fill_text
        }).then(res => {
          obj.red_line_price = fill_text
          obj.can_edit = false
          loading.close()
          this.$message.success('操作成功')
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    showInput(obj) {
      obj.can_edit = true
    }
  }
}
</script>

<style scoped>
.app_main {
  padding: 0 20px;
  margin-top: 20px;
}

.mailTable {
  width: 90%;
  margin: 10px auto;
}

.mailTable tr td {
  height: 60px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 10px 10px 0px 10px;
  border-bottom: 1px solid #E6EAEE;
  width: 250px;
  border-right: 1px solid #E6EAEE;
}

/*.mailTable tr td div {*/
/*  width: 250px;*/
/*}*/

.mailTable tr td div .el-form-item {
  margin-bottom: 10px;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}


/deep/ .el-input.is-disabled .el-input__inner {
  background-color: white;
  color: black;
}

.align-start {
  text-align: left;
}

/*.table-box {*/
/*  height: 100vh;*/
/*}*/
</style>
